package com.dhcc.core.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.interceptor.BackendInterceptor;
import com.dhcc.core.framework.interceptor.DemoAccountInterceptor;

/**
 * Mvc配置
 * 
 * @ClassName: MvcConfig
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午9:42:12
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Autowired
    SysProperties sysProperties;

    /**
     * 增加swagger的支持
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (sysProperties.getSwaggerOpen()) {
            registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
     // 小程序的业务域名校验文件不拦截（每个项目上都不同）
        registry.addResourceHandler("/B6A7LTPFNA.txt").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/static/**").addResourceLocations(
                "file:" + sysProperties.getStaticPath());
        registry.addResourceHandler("/**").addResourceLocations(
                "file:" + sysProperties.getSysHome());
    }

    /**
     * 增加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 后台权限拦截器
        registry.addInterceptor(new BackendInterceptor(sysProperties))
                .addPathPatterns("/" + sysProperties.getBackendPath() + "/**");
        // 演示帐号拦截器
        registry.addInterceptor(new DemoAccountInterceptor(sysProperties))
                .addPathPatterns("/**/update/**","/**/add/**","/**/delete/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }

}
